package com.blue.integration.serve.local;

import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.blue.core.util.StringUtil;
import com.blue.integration.serve.MailClient;
import com.blue.integration.serve.MailException;

/**
 * 本地发送邮件
 *
 * @author zhengjin
 * @since 1.0 2017年11月16日
 */
public class LocalMailClient implements MailClient, InitializingBean
{
	private static Logger logger = LoggerFactory.getLogger(LocalMailClient.class);

	private String from;
	private String host;
	private int port;
	private String username;
	private String password;
	private int timeout = 60000;
	private boolean auth = false;

	private JavaMailSenderImpl sender;

	public LocalMailClient()
	{
	}

	@Override
	public void send(String email, String title, String content, boolean html) throws MailException
	{
		MimeMessage message = sender.createMimeMessage();
		try
		{
			MimeMessageHelper helper = new MimeMessageHelper(message, html, StringUtil.UTF8);
			helper.setFrom(from);
			helper.setTo(email);
			helper.setSubject(title);
			helper.setText(content, html);
			sender.send(message);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new MailException("发送邮件失败");
		}
		logger.info("发送邮件成功：{}", email);
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		sender = new JavaMailSenderImpl();
		sender.setHost(host);
		sender.setPort(port);
		sender.setUsername(username);
		sender.setPassword(password);
		sender.setDefaultEncoding(StringUtil.UTF8);

		Properties prop = new Properties();
		prop.put("mail.smtp.timeout", timeout);
		prop.put("mail.smtp.auth", auth);
		sender.setJavaMailProperties(prop);
	}

	public void setFrom(String from)
	{
		this.from = from;
	}

	public void setHost(String host)
	{
		this.host = host;
	}

	public void setPort(int port)
	{
		this.port = port;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public void setTimeout(int timeout)
	{
		this.timeout = timeout;
	}

	public void setAuth(boolean auth)
	{
		this.auth = auth;
	}
}
